'use server';

import './style.scss';
import View from './view';
import { notFound, forbidden, redirect } from 'next/navigation';
import { BoardLayout, BoardSort, PostSearchType } from '@/constants/forum';
import BoardPostsRequest from '@/dtos/request/forum/board/postListRequest';
import { isAuthenticated } from '@/lib/api/auth';
import { fetchBoard, fetchPostList } from '@/lib/api/forum/board';
import { throwError, checkPermission } from '@/lib/utils/server';
import PermissionDenied from '../_component/PermissionDenied';

type Props = {
	params: Promise<{
		code: string;
	}>;
	searchParams: Promise<{
		page: number;
		perPage: number;
		prefix?: number;
		sort?: BoardSort;
		search: PostSearchType;
		keyword?: string;
	}>;
}

export default async function Board({ params, searchParams }: Props)
{
	const { code } = await params;

	if (!code) {
		return notFound();
	}

	const query = await searchParams;

	// 게시판 조회
	const board = await fetchBoard(code);

	if (!board || !board.data) {
		return notFound();
	}

	if (!board.data.isActive) {
		return forbidden();
	}

	const boardMeta = board.data.boardMeta;

	// 1:1 게시판은 로그인한 사용자만 접근 가능
	if (boardMeta.list.layout === BoardLayout.QnA && !await isAuthenticated()) {
		redirect('/login');
	}

	// 게시판 접근 권한 확인
	if (!await checkPermission(boardMeta.permission.boardAccess, board.data.boardManager)) {
		return <PermissionDenied _board={board.data} />;
	}

	query.page = Math.max(Number(query.page) || 1) as number;
	query.perPage = Math.max(Number(query.perPage) || (boardMeta.list.perPage || 10)) as number;
	query.prefix = (Number(query.prefix) || null) as number|undefined;
	query.sort = (Number(query.sort) || boardMeta.list.sort) as BoardSort|undefined;
	query.search = (Number(query.search) || PostSearchType.Subject) as PostSearchType;
	query.keyword = (query.keyword || '') as string|undefined;

	// 게시글 조회
	const boardPosts = await fetchPostList({
		boardID: board.data.id as number,
		boardCode: board.data.code as string,
		page: query.page as number,
		perPage: query.perPage as number,
		boardPrefixID: query.prefix as number|null|undefined,
		sort: query.sort as BoardSort|null|undefined,
		search: query.search as PostSearchType,
		keyword: query.keyword as string|null|undefined
	} as BoardPostsRequest);

	if (!boardPosts.success) {
		throwError(boardPosts);
	}

	return (
		<View _query={query} _board={board.data} _postList={boardPosts.data!} />
	);
}